package com.yeung.hibernate;

import com.yeung.hibernate.dao.BookShopDao;
import com.yeung.tx.UserAccountException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository
public class BookShopDaoImp implements BookShopDao {
    @Autowired
    private SessionFactory sessionFactory;

    //    HibernateDaoSupport
//    HibernateTemplate 不推荐使用, 会和spring进行耦合
    @Override
    public int findBookPriceByIsbn(int isbn) {
        String sql = "select price from Book where isbn= :isbn";
        Session session = getSession();
        Query query = session.createQuery(sql).setParameter("isbn", isbn);
        int size = (int) query.uniqueResult();
        return size;

    }

    private Session getSession() {
        return sessionFactory.getCurrentSession();
    }

    @Override
    public void updateBookStock(int isbn) throws Exception {
        //检查书的库存是否足够
        int stock = findBookStock(isbn);
        String sql = "update BookStock b set b.stock=b.stock -1 where b.isbn=:isbn";
        if (stock > 0)
            getSession().createQuery(sql).setParameter("isbn", isbn).executeUpdate();
        else throw new Exception("库存不足");
    }

    @Override
    public void updateUserAccount(String userName, int price) {
        int balance = findBalance(userName);
        String sql = "update Account set balance=balance - :balance where name=:name";

        if (balance == 0 || balance < price) try {
            throw new UserAccountException("余额不足");
        } catch (UserAccountException e) {

        }
        else
            getSession().createQuery(sql).setParameter("balance", price).setParameter("name", userName).executeUpdate();
    }

    @Override
    public int findBookStock(int isbn) {
        String sql = "select stock from BookStock   where isbn=:isbn";
        return (int) getSession().createQuery(sql).setParameter("isbn", isbn).uniqueResult();
    }

    @Override
    public int findBalance(String userName) {
        String sql = "select balance from Account  where name=:name";
        return (int) getSession().createQuery(sql).setParameter("name", userName).uniqueResult();
    }
}
